package udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class MyServer {

    public static void main(String[] args) {
        try {
            //1.创建服务器端DatagramSocket
            DatagramSocket server_ds = new DatagramSocket(9999);
            //2.创建要发送的数据包的对象
            String s = "通知：今天晚上7:00在401机房开会!";
            //把这个字符串打包成一个数据包
            DatagramPacket dp1 = new DatagramPacket(s.getBytes(), s.getBytes().length, InetAddress.getByName("localhost"), 7777);
            DatagramPacket dp2 = new DatagramPacket(s.getBytes(), s.getBytes().length, InetAddress.getByName("localhost"), 6666);

            //3.发送
            server_ds.send(dp1);
            server_ds.send(dp2);
            //4.接收客户端的数据包
            for (int i = 0; i < 2; i++) {
                byte[] buff = new byte[1024];
                DatagramPacket dp = new DatagramPacket(buff, buff.length);
                server_ds.receive(dp);
                System.out.println("接收的消息是：");
                System.out.println(new String(dp.getData(), 0, dp.getLength()));
                System.out.println(new String(" From:" + dp.getAddress() + " port:" + dp.getPort() + " length:" + dp.getLength() + "字节"));
            }
            //5.给服务器发送消息
            //5.关闭
            server_ds.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
